//
//  EQScrollCardView.swift
//  EQQuestionBank
//
//  Created by Macx on 2018/8/5.
//  Copyright © 2018年 FanWeiJian. All rights reserved.
//

import UIKit
import RxSwift
import SnapKit

let padding : CGFloat = 58.0

class EQScrollCardView: UIView {
    
    var zMargin : CGFloat = 0
    var xMargin: CGFloat = 0
    var cardAlpha : CGFloat = 0
    var angle : CGFloat = 0
    var _cardDataArray : [EQQuestionModel] = []
    var _index : Int = 0
    var _cardViewArray : [EQCardView] = [] //存储底部的cardView
    var _slideCardViewArray : [EQCardView] = []//存储滑动的cardView

    convenience init(frame: CGRect, zMargin: CGFloat, xMargin: CGFloat, alpha: CGFloat, angle: CGFloat){
        self.init(frame: frame)
        self.zMargin = zMargin
        self.xMargin = xMargin
        self.cardAlpha = alpha
        self.angle = angle
        
        _bottomView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
        
        _scrollView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
        
        //设置叠加视图的透视投影
        var sublayerTransform = CATransform3DIdentity
        sublayerTransform.m34 = -0.003
        _bottomView.layer.sublayerTransform = sublayerTransform
    }
    
    open func setCardData(datas: [EQQuestionModel]){
        _cardDataArray.removeAll()
        _cardViewArray.forEach({$0.removeFromSuperview()})
        _cardViewArray.removeAll()
        _slideCardViewArray.forEach({$0.removeFromSuperview()})
        _slideCardViewArray.removeAll()
        
        if (_cardDataArray.count == 0){
            _index = datas.count - 1
        }
        _cardDataArray.append(contentsOf: datas)
        if _cardDataArray.count > 0 {
            loadBotttomView()
            loadCardView(count: _cardDataArray.count)
        }
    }
    
    
    private func loadBotttomView(){
        
//        if _cardDataArray.count > 10 {
//            return
//        }
        let width = self.frame.width
        let height = self.frame.height
        
        //初始化四张卡片（如果要显示的卡片>4,否则就初始化显示的卡片张数）
        let count = _cardDataArray.count < 4 ? _cardDataArray.count : 4
        for index in 0..<count {
            let point = CGPoint(x: 0, y: -CGFloat(index) * height / xMargin)
            let zPosition =  -CGFloat(index) * height / zMargin
            
            //实例化CardView
            let card = EQCardView()
            card.frame = CGRect(x: point.x, y: point.y, width: width, height: height - padding)
            //card setdata
            card.setCardData(mode: _cardDataArray[index])

            
            if index < 3 {
                card.layer.zPosition = zPosition
                card.alpha = 1
            }else{
                card.layer.zPosition = -288
                card.alpha = 0
            }
            
            if index == 0 {
                card.isHidden = true
            }
            
            _cardViewArray.insert(card, at: 0)
            _bottomView.addSubview(card)
        }

    }
    
    private func loadCardView(count: Int){
        let size = self.frame.size
        let width = size.width
        
        if _cardDataArray.count > 10 {
            _scrollView.contentSize = CGSize(width: width, height: size.height * CGFloat(count))
            _scrollView.setContentOffset(CGPoint(x:0 ,y: CGFloat(count+_index) * size.height), animated: false)
            
            let card = _slideCardViewArray.first
            card?.frame = CGRect(x: 0, y: CGFloat(_index) * size.height, width: size.width, height: size.height - padding)
            
            return
        }
        
        let point = CGPoint(x: 0, y: CGFloat(_cardDataArray.count - 1) * size.height)
        
        //实例化Card
        let card = EQCardView()
        card.frame = CGRect(x: point.x, y: point.y, width: size.width, height: size.width - padding)
        card.setCardData(mode: _cardDataArray[0])

        card.nextButton.rx.controlEvent(UIControlEvents.touchUpInside)
            .subscribe(onNext: {[weak self] (_) in
                if self!._index - 1 < 0 {
                    print("已经是最后一题")
                    EQHUD.showInfo("已经是最后一题")
                }else{
                    self!._scrollView.setContentOffset(CGPoint(x: 0, y: CGFloat(self!._index - 1) * size.height), animated: true)
                }

            }).disposed(by: rx.disposeBag)
        

        
        //
        _slideCardViewArray.insert(card, at: 0)
        _scrollView.addSubview(card)
        
        _scrollView.contentSize = _cardDataArray.count > 1
            ? CGSize(width: width, height: size.height * CGFloat(_cardDataArray.count))
            : CGSize(width: width, height: size.height * CGFloat(_cardDataArray.count + 1))
        _scrollView.contentOffset = CGPoint(x: 0, y: CGFloat(_cardDataArray.count - 1) * size.height)
    }
    
    lazy var _bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .clear
        self.addSubview(view)
        return view
    }()
    
    lazy var _scrollView: UIScrollView = {
        let sc = UIScrollView()
        sc.delegate = self
//        sc.autoresizingMask = true
        sc.isPagingEnabled = true
        sc.clipsToBounds = false
        sc.showsVerticalScrollIndicator = false
        sc.showsHorizontalScrollIndicator = false
        sc.backgroundColor = .clear
        sc.bounces = false
        self.addSubview(sc)
        return sc
    }()
}

extension EQScrollCardView: UIScrollViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offset_y = scrollView.contentOffset.y
        let height = scrollView.frame.height
        let width = scrollView.frame.width
        let currentIndex = offset_y / height

        //得到索引
        _index = currentIndex > CGFloat(Int(currentIndex)) ? Int(currentIndex) + 1 :  Int(currentIndex)
        
        if _index > _cardDataArray.count - 1 {
            _index = _cardDataArray.count - 1
            return
        }
        
        let card : EQCardView! = _slideCardViewArray.first
        if card == nil {return}
        
        //表示处于当前视图内
        if card.frame.origin.y < offset_y {
            if offset_y > CGFloat(_cardDataArray.count) * height - height{
                card.isHidden = true
            }else {
                card.isHidden = false
                card.frame = CGRect(x: 0, y: CGFloat(_index) * height, width: card.frame.width, height: card.frame.height)
                card.setCardData(mode: _cardDataArray[_cardDataArray.count-1-_index])
            }
        }
        else if (card.frame.origin.y - height < offset_y && offset_y <= card.frame.origin.y){
            card.isHidden = false
        }
        else {
            card.frame = CGRect(x: 0, y: CGFloat(_index) * height, width: card.frame.width, height: card.frame.height)
            card.setCardData(mode: _cardDataArray[_cardDataArray.count-1-_index])
        }
        
        let _select = _index - 3 > 0 ? (_index - 3) : 0
        
//        if _index == 0 {
//            card.nextButton.isHidden = true
//        }else{
//            card.nextButton.isHidden = false
//        }

        for i in _select..._index {
            //调整滚动视图图片的角度
            let origin_y = CGFloat(i) * height
            
            //调整叠加视图
            let moveCard = _cardViewArray[i - _select]
            moveCard.setCardData(mode: _cardDataArray[_cardDataArray.count-1-i])
            
            let rang_y = (origin_y - offset_y) / xMargin
            moveCard.frame = CGRect(x: 0, y: rang_y, width: width, height: height )
            
            // 如果超过当前滑动视图便隐藏
            if rang_y >= 0 {
                moveCard.isHidden = false
            }else {
                moveCard.isHidden = false
            }
            
             //调整弹压视图的z值
            let rang_z = -(offset_y - origin_y) / zMargin
            
            moveCard.layer.zPosition = rang_z
            
            //调整弹压视图透明度
            let alpha = 1.0 + (origin_y - offset_y) / cardAlpha
            
            if currentIndex -  2.0 <= CGFloat(i) && CGFloat(i) <= currentIndex {
                if _index - 1 == i {
                    moveCard.headerView.alpha = 0.75
                    moveCard.contentView.alpha = 0.75
                }else if _index - 2 == i {
                    moveCard.headerView.alpha = 0.5
                    moveCard.contentView.alpha = 0.5
                }else{
                    moveCard.headerView.alpha = 1
                    moveCard.contentView.alpha = 1
                }
                moveCard.alpha = 1
            }else if currentIndex - 2 > CGFloat(i) && currentIndex - 3 < CGFloat(i) {
                moveCard.alpha = alpha
            }else {
                moveCard.alpha = 0
            }
            
        }
        
    }
    
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        _slideCardViewArray.forEach { (card) in
            card.layer.zPosition = 0
        }
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        
    }
    
}
